// 库存请求制单
import React from 'react';
import { Card, Row, Col, Form, DatePicker, Select, Input, Button, message, Popconfirm, Dropdown, Menu } from 'antd';
import { $http } from 'containers/config/https';
import Moment from 'moment';
import DetailReview from './component/DetailReview';
import InquireWarehouseVoucher from './component/InquireWarehouseVoucher';
import RequestConsume from './component/RequestConsume';
import RequestForm from './component/RequestForm';
import RequestBound from './component/RequestBound';
import './style/index.less';
import { printStkRequest } from '../commonPrint/stkPrint';

const { Option } = Select;
const { TextArea } = Input;

// function isObjEqual(o1,o2){
//     var props1 = Object.getOwnPropertyNames(o1);
//     var props2 = Object.getOwnPropertyNames(o2);
//     if (props1.length != props2.length) {
//         return false;
//     }
//     for (var i = 0,max = props1.length; i < max; i++) {
//         var propName = props1[i];
//         if (o1[propName] !== o2[propName]) {
//             return false;
//         }
//     }
//     return true;
// }
const InPurPlan = Form.create()(
    class extends React.Component {
        constructor() {
            super();
            this.state = {
                userInfo: {},
                SelectData: {}, // 下拉框数据
                detailInfo: [], // 明细列表数据
                rowId: '', // 入库单Id
                tacitlyApproveData: {}, // 界面的默认数据
                pageSize: 10,
                page: 1,
                total2: 0,
                User: JSON.parse(window.sessionStorage.userData),
                statusCode: '',
                statusId: '',
                inOpLocDr: '',
                toLoc: '',
                frLocID: '',
                filterLoc: JSON.parse(window.sessionStorage.userData).locID,
                operation: false,
                requestId: '',//当前查询的id
                stkCatID: '',
                ChineseEnglishSize: {}, //中英翻译
            };
            this.myRef1 = React.createRef();
            this.myRef2 = React.createRef();
            this.myRef3 = React.createRef();
            this.myRef4 = React.createRef();
            this.myRef5 = React.createRef();
            this.myRef6 = React.createRef();
            this.myRef7 = React.createRef();
            this.myRef8 = React.createRef();
            this.myRef9 = React.createRef();
        }

        componentDidMount() {
            // 初始化数据
            this.getSelectData();
            this.getTacitlyApproveData();
            this.getInOpLocDr();
        }

        componentWillUnmount() {
            // 组件销毁前将静止让setState修改state的状态
            this.setState = (state, callback) => { return; }
        }

        onRef = (ref) => {
            this.childModal = ref;
        };

        detailOnRef = (ref) => {
            this.childDetail = ref;
        };

        // 获取下拉框的数据
        getSelectData() {
            let data = {
                params: []
            };
            $http.post('urlS', this, {
                code: "02020110",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({ SelectData: res })
                    } else {
                        this.setState({ SelectData: {} })
                    }
                }
            })
        }

        // 保存
        saveHandle = () => {
            let { ChineseEnglishSize } = this.state;
            if (this.childDetail.state.data.length < 1) {
                message.error(ChineseEnglishSize.StockRequestFormdetailUnitTips ? ChineseEnglishSize.StockRequestFormdetailUnitTips.descripts : "明细列表不能为空")
            } else {
                // if(this.childDetail.state.stockID){
                //     let newObj =  this.childDetail.checkFormData();
                //     let beforeObj = this.childDetail.initialDataObj();
                //     if (!isObjEqual(newObj,beforeObj)){
                //         message.error('有未保存的数据，请先保存');
                //         return
                //     }
                // }
                this.props.form.validateFields((errors, values) => {
                    let obj = JSON.parse(JSON.stringify(values));
                    if (errors == null) {
                        let userList = this.state.userInfo ? this.state.userInfo : undefined;
                        let remark = this.props.form.getFieldValue('remark2');
                        let listId = this.childModal.state.rowId;
                        let data = {
                            params: [{
                                stkReqID: listId ? listId : this.state.statusId ? this.state.statusId : '',
                                frLocID: obj.frLoc ? obj.frLoc : userList.frLocID ? userList.frLocID : '',
                                toLocID: obj.toLoc ? obj.toLoc : userList.toLocID ? userList.toLocID : '',
                                stkCatID: obj.stkCat ? obj.stkCat : '',
                                remark: remark ? remark : '',
                                reqMethods: "手工建单",
                                detail: this.childDetail.state.data
                            }]
                        };
                        $http.post('urlS', this, {
                            code: "02020111",
                            data: data,
                            success: function (res) {

                                if (+res.errorCode === 0) {
                                    this.setState({ statusCode: res.result.main.stateID, statusId: res.result.main.stkReqID });
                                    this.childModal.setState({ tableData: [], total: 0 });
                                    // 成功提示
                                    message.success(res.errorMessage);
                                    this.getEchoData(res.result.main.stkReqID);
                                }
                            },
                            error: function (err) {
                                console.log(err)
                            }
                        })
                    }
                })
            }
        };

        // 保存成功后根据返回回来的inOperateID重新查找数据
        getEchoData(id) {
            // 重置表单
            this.props.form.resetFields(); //清空所有
            this.setState({ rowId: id }); // 将行id保存起来
            let data = {
                params: [
                    {
                        stkReqID: id ? id : this.state.requestId ? this.state.requestId : undefined
                    }
                ],
                pagination: [
                    {
                        pageSize: this.state.pageSize,
                        currentPage: this.state.page,
                    }
                ],
            };
            $http.post('urlS', this, {
                code: "02020113",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        for (let i = 0; i < res.detail.rows.length; i++) {
                            res.detail.rows[i].key = i + "main";
                        }
                        this.setState({ userInfo: res.main, detailInfo: res.detail.rows, frLocID: res.main.frLocID, total2: res.detail.total, requestId: res.main.stkReqID });
                        // this.props.form.setFieldsValue(res.result[0].mainInfo[0]); // 将查询出来的数据回显
                    } else {
                        this.setState({ userInfo: {}, detailInfo: [] });
                    }
                }
            })
        }

        // 获取到入库部门的值
        getInOpLocDr = () => {
            let inOpLocDr = this.props.form.getFieldValue('frLoc');
            let toLoc = this.props.form.getFieldValue('toLoc');
            let frLocID = this.props.form.getFieldValue('frLoc');
            let stkCatID = this.props.form.getFieldValue('stkCat');
            this.setState({ inOpLocDr: inOpLocDr, toLoc, stkCatID, frLocID });
            return toLoc
        }

        // 点击查询显示弹框
        inquireHandle = () => {
            this.getInOpLocDr();
            this.childModal.showModal(this.state.ChineseEnglishSize);
        };

        // 重置所有内容
        resetFieldsAll() {
            this.props.form.resetFields(); //清空所有
            this.setState({
                userInfo: {}, detailInfo: [], rowId: "", statusCode: '', statusId: '', operation: false, filterLoc: '', requestId: '',
                toLoc: '', stkCatID: '', frLocID: '', inOpLocDr: ''
            });
            this.childDetail.resetFields();
            this.childDetail.deleteData();
            this.childModal.handleUncheck();
            this.childModal.setState({ tableData: [], rowId: '' });
        }

        // 重置表单
        resetFields = () => {
            this.resetFieldsAll();
        };

        verificationObj() {
            for (var i in this.childDetail.state.userInfo) {
                return true;
            }
            return false
        }
        // 页码改变的回调，参数是改变后的页码及每页条数 入库单详情
        onChange = (page, pageSize) => {
            this.setState({ page: page, pageSize: pageSize }, () => {
                // 重新调用查询方法
                this.getEchoData();
            });
        };

        onShowSizeChange = (current, size) => {
            this.setState({ page: current, pageSize: size }, () => {
                // 重新调用查询方法
                this.onChange(current, size);
            })
        };

        // 删除
        handleDelete = () => {
            let data2 = {
                params: {
                    detail: [{
                        stkReqDetailID: this.childDetail.state.userInfo ? this.childDetail.state.userInfo.stkReqDetailID : undefined,
                    }]
                }
            };
            let data3 = {
                params: {
                    main: [
                        {
                            stkReqID: this.childModal.state.rowId ? this.childModal.state.rowId : this.state.statusId ? this.state.statusId : undefined,
                        }
                    ]
                }
            };
            $http.post('urlS', this, {
                code: "02020114",
                data: this.verificationObj() ? data2 : data3,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        message.success(res.errorMessage);
                        this.resetFieldsAll();
                        this.childModal.setState({ tableData: [], total: 0 })
                    }
                }
            })
        };

        // 获取界面默认值
        getTacitlyApproveData() {
            let data = {
                params: []
            };
            $http.post('urlS', this, {
                code: "02020054",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({ tacitlyApproveData: res.result[0] })
                    } else {
                        this.setState({ tacitlyApproveData: {} })
                    }
                }
            })
        }

        //完成
        accomplish = () => {
            let userStkReqID = this.state.userInfo.stkReqID ? this.state.userInfo.stkReqID : undefined;
            let data = {
                params: [{
                    stkReqID: this.state.statusId ? this.state.statusId : userStkReqID
                }]
            };
            $http.post('urlS', this, {
                code: "02020115",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        message.success(res.errorMessage);
                        this.setState({ statusCode: '' });
                        this.getEchoData(res.result.main.stkReqID);
                        this.childModal.setState({ tableData: [], total: 0 })
                    }
                }
            })
        };

        //取消完成
        offAccomplish = () => {
            let userStkReqID = this.state.userInfo.stkReqID ? this.state.userInfo.stkReqID : undefined;
            let data = {
                params: [{
                    stkReqID: this.state.statusId ? this.state.statusId : userStkReqID
                }]
            };
            $http.post('urlS', this, {
                code: "02020116",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        message.success(res.errorMessage);
                        this.getEchoData(res.result.main.stkReqID);
                        this.childModal.setState({ tableData: [], total: 0 })
                    }
                }
            })
        };

        //筛选科室
        filterLoc = (e) => {
            // let toLoc = this.props.form.getFieldValue('toLoc');
            this.setState({ filterLoc: e });
        };

        onSelectRef = (ref) => {
            this.childSelect = ref;
        };

        onConsumeRef = (ref) => {
            this.childConsume = ref;
        };

        onBoundRef = (ref) => {
            this.childBoundR = ref;
        };

        //显示依据请求单弹窗
        requestForm = () => {
            this.childSelect.showModal(this.state.ChineseEnglishSize);
        };

        //显示依据消耗弹框
        requestConsume = () => {
            this.childConsume.showModal(this.state.ChineseEnglishSize);
        };

        //显示依据上下限弹框
        requestBoundT = () => {
            this.childBoundR.showModal(this.state.ChineseEnglishSize);
        };

        operationNo = () => {
            this.setState({ operation: true })
        };
        
        operationOFF = () => {
            this.setState({ operation: false })
        };

        changeStkCat = (v) => {
            this.setState({ stkCatID: v })
        };

        //获取中英版
        getChineseEnglishSize = (v) => {
            this.setState({ ChineseEnglishSize: v })
        }

        render() {
            const formItemInput = {
                labelCol: { span: 6 },
                wrapperCol: { span: 18 },
            };
            const { getFieldDecorator } = this.props.form;
            let userInfo = this.state.userInfo ? this.state.userInfo : {};
            let user = this.state.User.locID ? this.state.User.locID : undefined;
            let userStatusCode = this.state.userInfo.stateID ? this.state.userInfo.stateID : '';
            let { ChineseEnglishSize } = this.state;
            const menu = (
                <Menu>
                    <Menu.Item>
                        <a rel="noopener noreferrer" onClick={this.requestForm} >
                            {ChineseEnglishSize.StockRequestFormAccordingTo ? ChineseEnglishSize.StockRequestFormAccordingTo.descripts : '依据请求单'}
                        </a>
                    </Menu.Item>
                    <Menu.Item>
                        <a rel="noopener noreferrer" onClick={this.requestConsume} >
                            {ChineseEnglishSize.StockRequestFormconsumption ? ChineseEnglishSize.StockRequestFormconsumption.descripts : '依据消耗'}
                        </a>
                    </Menu.Item>
                    <Menu.Item>
                        <a rel="noopener noreferrer" onClick={this.requestBoundT}>
                            {ChineseEnglishSize.StockRequestFormlimits ? ChineseEnglishSize.StockRequestFormlimits.descripts : '依据库存上下限'}
                        </a>
                    </Menu.Item>
                </Menu>
            );
            return (
                <div className="inPurPlan">
                    <Card
                        size="small"
                        title={<div className="card-title-left-icon"><div></div>{ChineseEnglishSize.StockRequestFormstockRequestForm ? ChineseEnglishSize.StockRequestFormstockRequestForm.descripts : '库存请求制单'}</div>}
                    >
                        <Row>
                            <Col span={18} className="top-form">
                                <Form>
                                    <Row>
                                        <Col span={8}>
                                            <Form.Item label={ChineseEnglishSize.StockRequestFormtoLoc ? ChineseEnglishSize.StockRequestFormtoLoc.descripts : '请求科室'} {...formItemInput}>
                                                {getFieldDecorator('toLoc', {
                                                    initialValue: userInfo.toLocID ? userInfo.toLocID + '' : user,
                                                    rules: [{ required: ChineseEnglishSize.StockRequestFormtoLoc ? ChineseEnglishSize.StockRequestFormtoLoc.required == 'Y' ? true : false : false, message: ChineseEnglishSize.StockRequestFormtoLoc ? ChineseEnglishSize.StockRequestFormtoLoc.message : '请求科室不能为空' }]
                                                })(
                                                    <Select showSearch allowClear placeholder={ChineseEnglishSize.StockRequestFormtoLocTips ? ChineseEnglishSize.StockRequestFormtoLocTips.descripts : '请选择请求科室'} onChange={this.filterLoc} disabled={this.state.detailInfo.length > 0 || this.state.operation ? true : false}>
                                                        {this.state.SelectData.loc && this.state.SelectData.loc.map(item => {
                                                            return <Option key={item.id} value={item.id} >{item.descripts}</Option>
                                                        })}
                                                    </Select>
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={8}>
                                            <Form.Item label={ChineseEnglishSize.StockRequestFormNO ? ChineseEnglishSize.StockRequestFormNO.descripts : '请求单号'} {...formItemInput}>
                                                {getFieldDecorator('NO', {
                                                    initialValue: userInfo.stkReqNO ? userInfo.stkReqNO : undefined,
                                                })(
                                                    <Input disabled />
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={8}>
                                            <Form.Item label={ChineseEnglishSize.StockRequestFormstkCatID ? ChineseEnglishSize.StockRequestFormstkCatID.descripts : '库存大类'} {...formItemInput}>
                                                {getFieldDecorator('stkCat', {
                                                    initialValue: userInfo.stkCatID ? userInfo.stkCatID + '' : undefined,
                                                    rules: [{ required: false, message: '库存大类不能为空' }]
                                                })(
                                                    <Select showSearch allowClear placeholder={ChineseEnglishSize.StockRequestFormstkCatTips ? ChineseEnglishSize.StockRequestFormstkCatTips.descripts : '请选择库存大类'} onChange={this.changeStkCat}>
                                                        {this.state.SelectData.stkCat && this.state.SelectData.stkCat.map(item => {
                                                            return <Option key={item.id} value={item.id}>{item.descripts}</Option>
                                                        })}
                                                    </Select>
                                                )}
                                            </Form.Item>
                                        </Col>
                                    </Row>
                                    <Row>
                                        <Col span={8}>
                                            <Form.Item label={ChineseEnglishSize.StockRequestFormfrLoc ? ChineseEnglishSize.StockRequestFormfrLoc.descripts : '供给科室'} {...formItemInput}>
                                                {getFieldDecorator('frLoc', {
                                                    initialValue: userInfo.frLocID ? userInfo.frLocID + '' : undefined,
                                                    rules: [{ required: ChineseEnglishSize.StockRequestFormfrLoc ? ChineseEnglishSize.StockRequestFormfrLoc.required == 'Y' ? true : false : false, message: ChineseEnglishSize.StockRequestFormfrLoc ? ChineseEnglishSize.StockRequestFormfrLoc.message : '供给科室不能为空' }]
                                                })(
                                                    <Select showSearch allowClear placeholder={ChineseEnglishSize.StockRequestFormfrLocTips ? ChineseEnglishSize.StockRequestFormfrLocTips.descripts : '请选择供给科室'} onSelect={this.getInOpLocDr} disabled={this.state.detailInfo.length > 0 || this.state.operation ? true : false} >
                                                        {this.state.SelectData.loc && this.state.SelectData.loc.filter((v) => v.id !== this.state.filterLoc).map(item => {
                                                            return <Option key={item.id} value={item.id} >{item.descripts}</Option>
                                                        })}
                                                    </Select>
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={8}>
                                            <Form.Item label={ChineseEnglishSize.StockRequestFormcrStartDate ? ChineseEnglishSize.StockRequestFormcrStartDate.descripts : '制单日期'} {...formItemInput}>
                                                {getFieldDecorator('createDate', {
                                                    initialValue: userInfo.createDate ? Moment(userInfo.createDate, 'YYYY-MM-DD') : Moment(),
                                                })(
                                                    <DatePicker style={{ width: '100%' }} format="YYYY-MM-DD" disabled />
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={8}>
                                            <Form.Item label={ChineseEnglishSize.StockRequestFormcreateTime ? ChineseEnglishSize.StockRequestFormcreateTime.descripts : '制单时间'} {...formItemInput}>
                                                {getFieldDecorator('createTime', {
                                                    initialValue: userInfo.createTime ? userInfo.createTime : undefined,
                                                })(
                                                    <Input disabled />
                                                )}
                                            </Form.Item>
                                        </Col>
                                    </Row>
                                    <Row>
                                        <Col span={8}>
                                            <Form.Item label={ChineseEnglishSize.StockRequestFormcreatePerson ? ChineseEnglishSize.StockRequestFormcreatePerson.descripts : '制单人'} {...formItemInput}>
                                                {getFieldDecorator('NO', {
                                                    initialValue: userInfo.createUserName ? userInfo.createUserName : undefined,
                                                })(
                                                    <Input disabled />
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={8}>
                                            <Form.Item label={ChineseEnglishSize.StockRequestFormstatus ? ChineseEnglishSize.StockRequestFormstatus.descripts : '单据状态'} {...formItemInput}>
                                                {getFieldDecorator('stkCat2', {
                                                    initialValue: userInfo.stateID ? userInfo.stateID : undefined,
                                                    rules: [{ required: false }]
                                                })(
                                                    <Select showSearch allowClear disabled>
                                                        {this.state.SelectData.state && this.state.SelectData.state.map(item => {
                                                            return <Option key={item.id} value={item.id}>{item.descripts}</Option>
                                                        })}
                                                    </Select>
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={8}>
                                            <Form.Item label={ChineseEnglishSize.StockRequestFormremark2 ? ChineseEnglishSize.StockRequestFormremark2.descripts : '备注'} {...formItemInput}>
                                                {getFieldDecorator('remark2', {
                                                    initialValue: userInfo.remark ? userInfo.remark : undefined,
                                                })(
                                                    <TextArea rows={1} style={{ width: '100%' }} />
                                                )}
                                            </Form.Item>
                                        </Col>
                                    </Row>
                                </Form>
                            </Col>
                            <Col span={5} style={{ marginLeft: '33px' }}>
                                <Row style={{ marginBottom: '20px', marginTop: '5px' }}>
                                    <Button style={{ marginRight: '30px' }} onClick={this.inquireHandle}>{ChineseEnglishSize.StockRequestFormsearch ? ChineseEnglishSize.StockRequestFormsearch.descripts : '查询'}</Button>
                                    <Button type="primary" style={{ marginRight: '30px' }} onClick={this.saveHandle}>{ChineseEnglishSize.StockRequestFormsave ? ChineseEnglishSize.StockRequestFormsave.descripts : '保存'}</Button>
                                    <Button disabled={this.state.statusCode == 10 ? false : userStatusCode == 10 ? false : true} onClick={this.accomplish}>{ChineseEnglishSize.StockRequestFormaccomplish ? ChineseEnglishSize.StockRequestFormaccomplish.descripts : '完成'}</Button>
                                </Row>
                                <Row>
                                    <Popconfirm title={ChineseEnglishSize.StockRequestFormresetTips ? ChineseEnglishSize.StockRequestFormresetTips.descripts : "重置后将初始化数据，你确定要重置吗?"} onConfirm={this.resetFields} okText={this.state.User.language == 'EN' ? "Yes" : '是'} cancelText={this.state.User.language == 'EN' ? "No" : '否'}>
                                        <Button style={{ marginRight: '30px' }} >{ChineseEnglishSize.StockRequestFormReset ? ChineseEnglishSize.StockRequestFormReset.descripts : '重置'}</Button>
                                    </Popconfirm>
                                    <Popconfirm title={ChineseEnglishSize.StockRequestFormdeleteTips ? ChineseEnglishSize.StockRequestFormdeleteTips.descripts : "删除不可恢复，你确定要删除吗?"} onConfirm={this.handleDelete} okText={this.state.User.language == 'EN' ? "Yes" : '是'} cancelText={this.state.User.language == 'EN' ? "No" : '否'}>
                                        <Button type="danger" style={{ marginRight: '30px' }}>{ChineseEnglishSize.StockRequestFormdelete ? ChineseEnglishSize.StockRequestFormdelete.descripts : '删除'}</Button>
                                    </Popconfirm>
                                    <Button disabled={this.state.statusCode == 20 ? false : userStatusCode == 20 ? false : true} onClick={this.offAccomplish}>{ChineseEnglishSize.StockRequestFormcancelComplete ? ChineseEnglishSize.StockRequestFormcancelComplete.descripts : '取消完成'}</Button>
                                </Row>
                                <Row style={{ marginTop: '20px' }}>
                                    <Dropdown overlay={menu} placement="bottomLeft">
                                        <Button>{ChineseEnglishSize.StockRequestFormauxiliaryForm ? ChineseEnglishSize.StockRequestFormauxiliaryForm.descripts : '库存请求辅助制单'}</Button>
                                    </Dropdown>
                                    <Button style={{ marginLeft: '45px' }} type="dashed" onClick={printStkRequest.bind(this, this.state.rowId)}>{ChineseEnglishSize.StockRequestFormprint ? ChineseEnglishSize.StockRequestFormprint.descripts : '打印'}</Button>
                                </Row>
                            </Col>
                        </Row>
                    </Card>
                    <DetailReview SelectData={this.state.SelectData} onRef={this.detailOnRef} frLocID={this.state.frLocID} detailInfo={this.state.detailInfo} handleThis={this} inOpLocDr={this.state.inOpLocDr} toLoc={this.state.toLoc} total={this.state.total2} page={this.state.page} pageSize={this.state.pageSize} stkCatID={this.state.stkCatID} />
                    <InquireWarehouseVoucher SelectData={this.state.SelectData} onRef={this.onRef} inOpLocDr={this.state.inOpLocDr} toLocID={this.state.toLoc} handleThis={this} />
                    <RequestConsume onRef={this.onConsumeRef} handleThis={this} />
                    <RequestForm onRef={this.onSelectRef} handleThis={this} />
                    <RequestBound onRef={this.onBoundRef} handleThis={this} />
                </div>
            )
        }
    }
);

export default InPurPlan;